package com.szp.drug.config;

import com.szp.drug.entity.DrugAdmin;
import com.szp.drug.component.service.api.DrugAdminService;
import com.szp.drug.entity.DrugRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * DrugUserDetailsService实现类 去实现SpringSecurity中的UserDetailsService类
 * @author SuZePing
 * @create 2021-02-22 10:48
 * @E-mail suzeping10@126.com
 */
@Component
public class DrugUserDetailsService implements UserDetailsService {

	@Autowired
	private DrugAdminService adminService;

	/**
	 * 通过account来获取SecurityAdmin[包括DrugAdmin对象,含前缀的roleName数组]
	 * @param username
	 * @return
	 * @throws UsernameNotFoundException
	 */
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		DrugAdmin selAdmin = adminService.getAdminByAccount(username);
		String adminId = selAdmin.getUserId();
		// 查询该管理员的角色
		List<DrugRole> assignedRoleList = adminService.getAssignedRole(adminId);
		// 把角色和权限放入List<GrantedAuthority>
		List<GrantedAuthority> authorities = new ArrayList<>();

		assignedRoleList.stream()
				.map(DrugRole::getRoleName)
				// 对于角色要加上"ROLE_"前缀
				.map(s -> "ROLE_" + s)
				.map(SimpleGrantedAuthority::new)
				.map(authorities::add)
				.count();

		// 返回SecurityAdmin对象 当中包括原始的DrugAdmin对象及List<GrantedAuthority>
		return new SecurityAdmin(selAdmin,authorities);
	}

}
